import Vue      from 'vue'
// import Router   from 'vue-router'-改成cdn引入
import login    from '@/views/login'

//路由集合  && views 引入
import index    from '@/views/home/index' //首页公共模块
import company  from './company' //企业模块
import project  from './project' //业务模块
import journal  from './journal' //日志模块
import settings from './settings' //设置模块



Vue.use(VueRouter)

const router = new VueRouter({
  //为了获得历史路由设计
  // mode: 'history',
  scrollBehavior(to,from,savedPosition){
      // console.log(to,from)
      /*有缓存的页面，重新回到原位置*/
      if (to.meta.keepAlive) {
        document.querySelector('.el-main').scrollTop =to.meta.savedPosition
      }
      else{
        /*content-filed，el-main，方便页面之间跳转时，每个页面都是从最顶的位置开始显示*/
        document.querySelector('.el-main').scrollTop =0
      }
  },
	//定义所有的路由
  routes: [
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: { requiresAuth: false }
    },
     {
      path: '/',
      name: 'index',
      component: index,
      meta: { requiresAuth: true },
      children:[
          {
            path            : '/homework',
            component       : ()=>import('@/views/homework/index'),//1.工作台
            name            : 'homework',
            meta            :  {
                                 requiresAuth:true,
                                 title:'首页'
                               }
         },
  
         ...company,                                             //2.企业
          ...project,                                             //3.业务
          {
            path            : '/examine',
            component       : ()=>import('@/views/examine/index'),//4.审批
            name            : 'examine',
            meta            :  {
                                 requiresAuth:true,
                                 keepAlive:true,
                                 title:'审批'
                               }
         },
         {
            path            : '/examine/detail',
            component       : ()=>import('@/views/examine/detail_unstart'),//4.审批详情-还未审批
            name            : 'ExaDetail_unstart',
            meta            :  {
                                 requiresAuth:true,
                                 title:'审批/详情'
                               }
         },
         {
            path            : '/userlist',
            component       : ()=>import('@/views/userlist/index'),//5.用户
            name            : 'userlist',
            meta            :  {
                                 requiresAuth:true,
                                 title:'用户列表'
                               }
         },
         ...journal,                                              //6.日志
         ...settings,                                             //7.设置
         
      ]
    },
    
  ],

})

/*路由拦截器设置-before*/
router.beforeEach((to, from, next) => {
    // console.log(to,from)
    /*有缓存的页面，重新回到原位置*/
    if(from.meta.keepAlive == true){
        from.meta.savedPosition = document.querySelector('.el-main').scrollTop
    }

    /*修改后提交到列表页 设置不缓存，其余页面返回列表页设置缓存*/
    if(from.meta.modifyCacheRoute){
        router.app.$store.commit('setcacheRoute', []);
    }
    else{
        router.app.$store.commit('setcacheRoute',router.app.Global.cacheRouteArr );
    }
    let token = sessionStorage.getItem('token')
    //1.登录权限判断
    if(to.meta.requiresAuth) {
        //验证token，存在才跳转
        if(token) {
            next()
        } 
        else {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }
    } 
    else{
        if(to.path === '/' ) {
            /*后退到login时拦截*/
            if(token){
                next({path:'/homework'})
            }
            //根目录（刚进入页面时）
            else{
                next({path: '/login'})
            }
        }
        else{
          // alert(to.path)
            next()
        }
    }
    /*2.非登陆条件下输入某个地址 需要先跳到登录页再跳转到相应页面*/
    if(to.matched.length == 0 ){
        next({path: '/login',query: { redirect: to.fullPath }})
    }
});

router.afterEach((to, from) => {
  // 设置面包屑
  let breadCrumbItems = []
  let homePageCrumb = {
    title: '首页',
    to: '/'
  }
  if(to.meta.title == '首页'){

  }
  else{
    breadCrumbItems.push(homePageCrumb)
  }
  
  if(to.meta.title) {
    let fullPathSplit = to.meta.title.split('/')
    // console.log(fullPathSplit)
    
        let sec_path = '/'+to.path.split('/')[1]
        //二级目录 需要link
        if(sec_path == '/company'  || sec_path == '/examine' ){
              fullPathSplit.forEach(( item, index ) => {
                let routerBreadCrumb = {
                  title: item,
                   to: (index == 0 ? sec_path : '' )
                   // to: (index == fullPathSplit.length - 1 ? to.path : '' )
                  
                }
                breadCrumbItems.push(routerBreadCrumb)
              });
        }
        //二级目录 需要为空
        else{
              fullPathSplit.forEach(( item, index ) => {
                let routerBreadCrumb = {
                  title: item,
                   to: (index == 0 ? '' : ( index == fullPathSplit.length - 1 ? to.path : sec_path) )
                   // to: (index == fullPathSplit.length - 1 ? to.path : '' )
                  
                }
                breadCrumbItems.push(routerBreadCrumb)
              });
        }
        
    // console.log(breadCrumbItems) 

  }
  // 更新到state
   router.app.$store.commit('setbreadcrumbItems', breadCrumbItems);
  //router.app.$store.dispatch('setbreadcrumbItems', breadCrumbItems)
})

export default router